﻿using AutoMapper;
using MediatR;
using ProcurementManagement.Applcation.Command.ProcureEnquiryCommand;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.ProcureEnquiryCommandHandlers
{
    /// <summary>
    /// 采购询价新增
    /// </summary>
    public class ProcureEnquiryCreateCommandHandlers : IRequestHandler<ProcureEnquiryCreateCommand, int>
    {
        protected readonly IProcureEnquiryRepository repository;
        protected readonly IInquiryVendorRepository vendorRepository;
        protected readonly IMapper mapper;
        protected readonly ISqlSugarClient db;

        public ProcureEnquiryCreateCommandHandlers(IProcureEnquiryRepository repository, IInquiryVendorRepository vendorRepository, IMapper mapper, ISqlSugarClient db)
        {
            this.repository = repository;
            this.vendorRepository = vendorRepository;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<int> Handle(ProcureEnquiryCreateCommand request, CancellationToken cancellationToken)
        {
            //开启事务
            db.Ado.BeginTran();
            try
            {
                var guids=Guid.NewGuid().ToString();
                request.dto.PEDocumentsNumber = guids;
                var pvadd = mapper.Map<ProcureEnquiry>(request.dto);
                await repository.AddAsync(pvadd);
                foreach (var item in request.dto.dtos)
                {
                    InquiryVendor vendor = new InquiryVendor
                    {
                        VendorName = item.VendorName,
                        AddName = request.dto.AddName,
                        AddTime = DateTime.Now,
                        VendorNum = item.VendorNum,
                        VendorPrice = item.VendorPrice,
                        SumPrice = item.SumPrice,
                        DeliveryDate = item.DeliveryDate,
                        PEDocumentsNumber = guids,
                        Office_Id = request.dto.Office_Id,
                        User_Id = request.dto.User_Id
                    };
                    await vendorRepository.AddAsync(vendor);
                }
                //提交事务
                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                //回滚事务
                db.Ado.RollbackTran();
                throw;
            }


        }
    }
}
